package com.spoplar.controller.backend;


import com.alipay.api.response.AlipayTradePayResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.spoplar.beans.AlipayTradePrecreateResponseBody;
import com.spoplar.dao.MerchantShopMapper;
import com.spoplar.dao.MerchantWxpayConfMapper;
import com.spoplar.pojo.*;
import com.spoplar.service.IMerchantShopService;
import com.spoplar.service.IWxpayService;
import com.spoplar.service.IalipayService;
import com.spoplar.service.ImerchantService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by spoplar on 18-1-29.
 */
@Controller
@RequestMapping("/demo")
public class DemoController {
    private Logger log = LoggerFactory.getLogger(DemoController.class);

    @Autowired
    private ImerchantService imerchantService;

    @Autowired
    private IalipayService ialipayService;

    @Autowired
    private IMerchantShopService iMerchantShopService;

    @Autowired
    private IWxpayService iWxpayService;

    @Autowired
    private MerchantWxpayConfMapper merchantWxpayConfMapper;

    @RequestMapping(value = "/qrcode.do",method = RequestMethod.GET)
    public void qrcode(HttpServletResponse response,HttpServletRequest request) throws IOException{
        String token="abc";

        MerchantShop merchantShop = iMerchantShopService.findByShopToken(token);

        MerchantAlipayConf merchantAlipayConf = imerchantService.findByToken(merchantShop.getMerPayToken());

        String outTradeNo = "ffff666fa889944458";
        String subject = "bbbb";
        String totalAmount = "10";
        String store_id = merchantAlipayConf.getPid();
        MerchantAlipayTrade trade = new MerchantAlipayTrade();
        trade.setOutTradeNo(outTradeNo);
        trade.setSubject(subject);
        trade.setTotalAmount(Integer.valueOf(totalAmount));
        trade.setStoreId(store_id);
        trade.setMerPayToken(merchantShop.getMerPayToken());
        trade.setShopPayToken(token);
        String qrcode = ialipayService.alipay_by_qrcode(merchantAlipayConf,trade);

        String val = qrcode;
        System.out.println(val);

        StringBuilder sb = new StringBuilder();
        sb.append("<html>");
        sb.append("<body>");
        sb.append("<h1>请输入金额</h1>");
        sb.append("</body>");

        sb.append("<script>");
        String url =  "setTimeout(function(){ window.location.href='" +val+ "'; },10000)";
        sb.append(url);
        sb.append("</script>");

        sb.append("</html>");
        System.out.println(sb.toString());

        //response.sendRedirect("show.do?val="+val+"&t="+Math.random());
        response.getWriter().println(sb.toString());

    }

    @RequestMapping(value = "/show.do",method = RequestMethod.GET)
    public void show(HttpServletRequest request,HttpServletResponse response) throws IOException {

        String token="abc";
        MerchantAlipayConf merchantAlipayConf = imerchantService.findByToken(token);
        Merchant merchant = imerchantService.findMerchantByToken(token);
        String outTradeNo = "667777000996666";
        String subject = "bbbb";
        String totalAmount = "10";
        String store_id = merchantAlipayConf.getPid();
        String authCode = "280814414670381465";

        MerchantAlipayTrade trade = new MerchantAlipayTrade();
        trade.setOutTradeNo(outTradeNo);
        trade.setSubject(subject);
        trade.setTotalAmount(Integer.valueOf(totalAmount));
        trade.setStoreId(store_id);
        trade.setAuthCode(authCode);
        trade.setMerPayToken(merchant.getPayToken());
        trade.setShopPayToken(token);

        AlipayTradePayResponse result = ialipayService.alipay_by_pay(merchantAlipayConf,trade);
        String body = result.getBody();
        response.getWriter().println("支付成功");

    }
    @RequestMapping(value = "/index.do",method = RequestMethod.POST)
    public void index(HttpSession session, HttpServletResponse response, HttpServletRequest request) throws IOException {

    }

    @RequestMapping(value="/wxMircro.do",method = RequestMethod.GET)
    public void wxMircro(HttpServletRequest request ,HttpServletResponse response){

        MerchantWxpayConf conf =  merchantWxpayConfMapper.selectByPrimaryKey(1);

        MerchantShop merchantShop = iMerchantShopService.findByShopToken("abc");

        HashMap<String,String> data = new HashMap<String,String>();
        data.put("out_trade_no", "12777772335488");
        data.put("body", "测试");
        data.put("total_fee", "1");
        data.put("auth_code", "134671644681269366");
        try {
            iWxpayService.micropay(conf,data,merchantShop);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @RequestMapping(value="/wxQrcode.do",method = RequestMethod.GET)
    public void wxQrcode(HttpServletRequest request ,HttpServletResponse response){
        MerchantWxpayConf conf =  merchantWxpayConfMapper.selectByPrimaryKey(1);
        MerchantShop merchantShop = iMerchantShopService.findByShopToken("abc");
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("body", "test");
        data.put("out_trade_no", "85462255153354");
        data.put("device_info", "");
        data.put("fee_type", "CNY");
        data.put("total_fee", "1");
        data.put("spbill_create_ip", "218.28.137.114"); //123.12.12.123
        data.put("notify_url", "http://www.spoplar.xyz/");
        data.put("trade_type", "NATIVE");
        data.put("product_id", "12");
        // data.put("time_expire", "20170112104120");

        try {
            iWxpayService.qrcodepay(conf,data,merchantShop);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    @RequestMapping(value="/wxquery.do",method = RequestMethod.GET)
    public void wxQuery(HttpServletRequest request ,HttpServletResponse response){
        MerchantWxpayConf conf =  merchantWxpayConfMapper.selectByPrimaryKey(1);
        HashMap<String,String> data = new HashMap<String,String>();
        data.put("out_trade_no", "85462255153354");
//        data.put("body", "测试");
//        data.put("total_fee", "1");
//        data.put("auth_code", "134520609830963420");
        try {
            iWxpayService.query(conf,data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @RequestMapping(value = "/wxvalidata.do",method = RequestMethod.GET)
    public void wxValidate(HttpServletRequest req,HttpServletResponse resp){
        String returnStr="<xml><appid><![CDATA[wx57302e3308f9ddaa]]></appid>\n" +
                "<bank_type><![CDATA[CFT]]></bank_type>\n" +
                "<cash_fee><![CDATA[1]]></cash_fee>\n" +
                "<fee_type><![CDATA[CNY]]></fee_type>\n" +
                "<is_subscribe><![CDATA[N]]></is_subscribe>\n" +
                "<mch_id><![CDATA[1316313901]]></mch_id>\n" +
                "<nonce_str><![CDATA[15ae1f6d140b40b09e626dad82d7e2cb]]></nonce_str>\n" +
                "<openid><![CDATA[oxCajsyH_OyRqUoQnHy6_1hRx_w0]]></openid>\n" +
                "<out_trade_no><![CDATA[85462255153354]]></out_trade_no>\n" +
                "<result_code><![CDATA[SUCCESS]]></result_code>\n" +
                "<return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "<sign><![CDATA[319F810EFDA1DF8A4C590E793AC0FF80AB6CFDC221A84AAEA45682CE8CF6526C]]></sign>\n" +
                "<time_end><![CDATA[20180208150533]]></time_end>\n" +
                "<total_fee>1</total_fee>\n" +
                "<trade_type><![CDATA[NATIVE]]></trade_type>\n" +
                "<transaction_id><![CDATA[4200000067201802089396140801]]></transaction_id>\n" +
                "</xml>";
        MerchantWxpayConf conf =  merchantWxpayConfMapper.selectByPrimaryKey(1);
        try {
            Map<String,String> data = WXPayUtil.xmlToMap(returnStr);
            System.out.println(data);
            iWxpayService.validate(conf,data);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
